<?php
/**
 * @return
 * @author yuncran@126.com
 */

namespace app\api\controller;

use app\BaseController;
use app\model\ConfigModel;
use app\model\UserModel;
use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;

class PayPal extends BaseController
{


    protected $client = 'https://api.sandbox.paypal.com/v1/oauth2/token';
    protected $payment = 'https://api.paypal.com/v1/oauth2/token';

//    protected $payment = 'https://api.sandbox.paypal.com/v1/payments/payment'; // 沙盒环境


    protected $apiContext;

//    private $clientId = 'AahK573eG2zp1L_-rfNlnGSzqF_giayL4suHg878tbDwSOS9N4UKAOKWCHtiRiK5gLRK1op0sOkqM_aJ';
//    private $clientSecret = 'ENm6Ty0GRz-U2DRHAVR6PkLUjryEIj_ni5zGpU2fsjUWPZXgBYh7toCOuZVUoteqiQ5yE2V-iKV_l3Jr';

    private $clientId = 'AahK573eG2zp1L_-rfNlnGSzqF_giayL4suHg878tbDwSOS9N4UKAOKWCHtiRiK5gLRK1op0sOkqM_aJ';

    private $clientSecret = 'ENm6Ty0GRz-U2DRHAVR6PkLUjryEIj_ni5zGpU2fsjUWPZXgBYh7toCOuZVUoteqiQ5yE2V-iKV_l3Jr';

    /**
     * 获取 access_token
     * @return mixed
     * @author yuncran@126.com\
     */
    public function getAccessToken()
    {
//        $clientId = 'Adppsnvxk_CE42t_kPgWJo7TzWoIok_o-Co0oPznFWFmOVIahlb2DjN23YgJPRDLGx-MKXJFrw4yLOS5';
//        $clientSecret = 'EIOKtq59Ysrkl-x_JMbkghxNOjcoy_STLJ9f1Y-R7BW7Wcll-O2RilD2VQOYVa4t2tZa7Jg2gKwvCxJy';
        $clientId = ConfigModel::where('name', 'example_paypal_key')->cache(true,60)->value('value');
        $clientSecret = ConfigModel::where('name', 'example_paypal_secret')->cache(true,60)->value('value');
        $client = new \GuzzleHttp\Client();
        // 获取访问令牌
        $response = $client->post($this->payment, [
            'auth' => [$clientId, $clientSecret],
            'form_params' => [
                'grant_type' => 'client_credentials'
            ]
        ]);
        return $data = json_decode($response->getBody(), true);
    }


    /**
     * xin
     * @return void
     * @author yuncran@126.com
     */
    public function addOrderCopy()
    {
        $param = $this->request->param();

        $xt_app_id = '10180';
        $xt_secret_key = '8235c5ba423c4d46aa68a5fc6205502e';

        $client = new \GuzzleHttp\Client();
        $url = 'https://nexpaysystem.com/api/system/external/payType';
        
        $response = $client->post( $url, [
            'headers' => [
                'xt-app-id' => $xt_app_id,
                'xt-secret-key' => $xt_secret_key,
            ],
            'json' => ['currency'=>'USD','total'=>$param['money']]
        ]);
        
        $res = $response->getBody()->getContents();

        if (!$res) return $this->renderError(lang('请求付款方式错误'));
        $res_array = json_decode($res, true);
        $result = array();
        foreach ($res_array['data'] as $key => $item) {
            if($item['code'] = 'paypal'){
                 $result =  $item ;
            }
        }
        if(empty($result)) return $this->renderError(lang('请求付款方式错误'));
        $accountId = $result['account']['id'];

        $order_id = order_no();
        // $response_data = [
        //     'order_id' => $order_id,
        //     'currency' => 'USD',
        //     'from_domain' => $this->request->domain(),
        //     'total' => $param['money'],
        //     'callback_url' => $this->request->root(true) . '/Home/callback_url',  //支付异步回调
        //     'success_url' => $this->request->root(true) . '/Home/callback_url', //成功跳转地址
        //     'cancel_url' => $this->request->root(true) . '/Home/callback_url',  //取消跳转地址
        //     'failure_url' => $this->request->root(true) . '/Home/payPalCallback?success=false&order_id=' . $order_id,   //失败跳转地址
        //     'accountId' => $accountId,
        //     'billing' => array(
        //         'country' => 'US',
        //         'email' => 'xxxxxxxx@qq.com',
        //     ),
        //     'shipping' => array(
        //         'country' => 'US',
        //         'email' => 'xxxxxxxx@qq.com',
        //     ),
        //     'product_data' => array(
        //         array(
        //             'post_name' => '123',
        //             'quantity' => 123,
        //             'price' => 123,
        //         )
        //     )
        // ];
        $response_data = array(
            'order_id' => $order_id,
            'currency' => 'USD',
            'from_domain' => $this->request->domain(),
            'customer_ip_address' => $this->request->ip(),
            'total' => $param['money'],
            'callback_url' => $this->request->root(true) . '/Home/callback_url',
            'success_url' => $this->request->domain() . '/pay/success.html', //成功跳转地址
            'cancel_url' =>  $this->request->domain() ,  //取消跳转地址
            'failure_url' =>  $this->request->domain()  .'/pay/fail.html',   //失败跳转地址
            'accountId' => $accountId,
            'billing' => array(
                'first_name' => 'Ga',
                'last_name' => 'gavino',
                'address_1' => '地址111',
                'address_2' => '',
                'country' => 'US',
                'state' => '123',
                'city' => '22',
                'postcode' => '14231',
                'email' => 'xxxxxxxx@qq.com',
                'phone' => '123123123123'
            ),
            'shipping' => array(
                'first_name' => 'Ga',
                'last_name' => 'gavino',
                'address_1' => '地址111',
                'address_2' => '',
                'country' => 'US',
                'state' => '123',
                'city' => '22',
                'postcode' => '14231',
                'email' => 'xxxxxxxx@qq.com',
                'phone' => '123123123123'
            ),
            'product_data' => array(
                array(
                    'post_name' => '123',
                    'quantity' => 123,
                    'price' => 123,
                    'type' => 'simple',
                    'image' => ''
                )
            )
        );

        $response_url = 'https://nexpaysystem.com/api/system/external/push';
        $response = $client->post($response_url, [
            'headers' => [
                'xt-app-id' => $xt_app_id,
                'xt-secret-key' => $xt_secret_key,
            ],
            'json' => $response_data
        ]);
        $statusCode = $response->getStatusCode();
        if ($statusCode != 200) {
            return $this->renderError(lang('请求失败'));
        }
        
        $user = UserModel::where('id', $this->uid)->field(['nickname'])->find();
        $save['order_sn'] = $order_id;
        $save['user_id'] = $this->uid;
        $save['type'] = $param['type'];
        $save['money'] = $param['money'];
        $save['gold_money'] = $param['money'];
        $save['merchant_id'] = $this->merchantId;
        $save['username'] = $user['nickname'];
        $save['email'] = $user['email'];        
        $resp = \app\model\RechargeModel::create($save);
        $result = json_decode($response->getBody()->getContents(), true);

        return $this->renderSuccess(['url' => $result['data']['link']], lang('请求成功'));
        
        die;
/******************** ↓ 旧接口 暂时不用 **************************/        
        return $this->renderSuccess($response->getBody()->getContents(), lang('请求成功'));      
        
        $url = 'https://core.htadminusre.xyz/prod-api/system/PayOrder/pushV2';
        $client = new \GuzzleHttp\Client();
        $user = UserModel::where('id', $this->uid)->field(['nickname'])->find();
        $order_id = order_no();
        $addData = [
            "mchid" => "10170",
            "order_id" => $order_id,
            "billing" => [
                "address_1" => "aaaaa",
                "address_2" => "aaa",
                "city" => "aa",
                "company" => "",
                "country" => "CN",
                "email" => "1947888082@qq.com",
                "first_name" => "gavino",
                "last_name" => "ga",
                "phone" => "1554654868",
                "postcode" => "99071",
                "state" => "CN2",
            ],
            "callback_url" => $this->request->root(true) . '/Home/callback_url',
            "cancel_url" => $this->request->root(true) . '/Home/payPalCallback?success=false&order_id=' . $order_id,
            "currency" => "USD",
            "customer_ip_address" => $this->request->ip(),
            "failure_url" => $this->request->root(true) . '/Home/payPalCallback?success=false&order_id=' . $order_id,
            "from_domain" => $this->request->domain(),

            "product_data" => [
                0 => [
                    "post_id" => 15663,
                    "post_name" => "2Pc Gold Vase for Home Decor,Flower vase for Decor,Geometric vases for centerpieces,Gold Glass vase for Wedding Decorations,Gold vases for centerpieces,Gold Test Tube vase (2Pcs 8.5 inch Gold)",
                    "post_slug" => "2pc-gold-vase-for-home-decorflower-vase-for-decorgeometric-vases-for-centerpiecesgold-glass-vase-for-wedding-decorationsgold-vases-for-centerpiecesgold-test-tube-vase-2pcs-8-5-inch-gold",
                    "quantity" => 1,
                    "price" => "25.99",
                    "post_content" => "",
                    "type" => "variable",
                    "attributes" => "a:1:{s:5:color:s:13:8.5 Inch Gold}",
                    "image" => "https://pic.rmb.bdstatic.com/bjh/914b8c0f9814b14c5fedeec7ec6615df5813.jpeg",
                ],
            ],
            "success_url" => $this->request->root(true) . '/Home/payPalCallback?success=true&order_id=' . $order_id,
            "total" => $param['money'],
        ];

        $response = $client->post($url, [
            'headers' => [
                'Accept' => '*/*',
                'Content-Type' => 'application/json',
                'Secret-Key' => '23e263f71a80445e9b5691da7f054bb9',
            ],
            'json' => $addData
        ]);
        $statusCode = $response->getStatusCode();
        if ($statusCode != 200) {
            return $this->renderError(lang('请求失败'));
        }
        $save['order_sn'] = $order_id;
        $save['user_id'] = $this->uid;
        $save['type'] = $param['type'];
        $save['money'] = $param['money'];
        $save['gold_money'] = $param['money'];
        $save['merchant_id'] = $this->merchantId;
        $save['username'] = $user['nickname'];
        $save['email'] = $user['email'];
        $resp = \app\model\RechargeModel::create($save);
        $result = json_decode($response->getBody()->getContents(), true);
        
        
        
        return $this->renderSuccess(['url' => $result['call_back']], lang('请求成功'));
    }



    public function addOrder()
    {
        $param = $this->request->param();
        $product = 'golds';
        $money = $param['money'];
        $shipping = 0;
        $total = $money;
        $description = 'User recharge';
        $add_order = order_no();
        // 创建支付
        $payer = new Payer();
        $payer->setPaymentMethod("paypal");
        $item = new Item();
        $item->setName($product)->setCurrency("USD")->setQuantity(1)->setPrice($money);

        $itemList = new ItemList();
        
        $itemList->setItems([$item]);

        $details = new Details();
        $details->setShipping($shipping)->setSubtotal($money);

        $redirectUrls = new RedirectUrls();
        $redirectUrls->setReturnUrl($this->request->root(true) . '/Home/payPalCallback?success=true&orderid=' . $add_order)
            ->setCancelUrl($this->request->domain() );

        $amount = new Amount();
        $amount->setCurrency("USD")
            ->setTotal($total)
            ->setDetails($details);

        $transaction = new Transaction();
        $transaction->setAmount($amount)
            ->setItemList($itemList)
            ->setDescription($description)
            ->setInvoiceNumber(uniqid());

        $payment = new Payment();

        $payment->setIntent('sale')
            ->setPayer($payer)
            ->setRedirectUrls($redirectUrls)
            ->setTransactions(array($transaction));

        try {
            $clientId = ConfigModel::where('name', 'example_paypal_key')->cache(true,60)->value('value');
            $clientSecret = ConfigModel::where('name', 'example_paypal_secret')->cache(true,60)->value('value');
            $apiContext = new ApiContext(
                new OAuthTokenCredential(
                    $clientId, // ClientID
                    $clientSecret // ClientSecret
                )
            );
            
            $apiContext->setConfig(
                array(
                    'mode' => 'live', // live,sandbox
                    'http.ConnectionTimeOut' => 30,
                )
            );
            $payment->create($apiContext);
             // dump($payment);die;
            $approvalUrl = $payment->getApprovalLink();
                 
            $user = UserModel::where('id',$this->uid)->field(['nickname','email'])->find();
            $save['order_sn'] = $add_order;
            $save['user_id'] = $this->uid;
            $save['type'] = $param['type'];
            $save['money'] = $money;
            $save['gold_money'] = $money;
            $save['merchant_id'] = $this->merchantId;
            $save['username'] = $user['nickname'];
            $save['email'] = $user['email'];

            $response = \app\model\RechargeModel::create($save);
            if (!$response) return $this->renderError(lang('充值失败'));
        } catch (\Exception $exception) {
            var_dump( $exception->getMessage() );
            var_dump(  $exception->getTraceAsString() );
        }

        $data['url'] = !empty($approvalUrl) ? $approvalUrl : '';
        return $this->renderSuccess($data, lang('请求成功'));
    }


    public function paypalNotice()
    {

        $content = file_get_contents("php://input");
        $log_file = 'public/data_log/pay' . date('Ymd', time()) . '.txt';
        $logs = "notice \r" . date("Y-m-d H:i:s", time()) . "\r\n" . $content;
        file_put_contents($log_file, $logs, FILE_APPEND);
        // 这里可以写一个日志，看一下接收到的数据
        if (!empty ($content)) {
            $log_file = 'public/data_log/pay' . date('Ymd', time()) . '.txt';
            $logs = "notice \r" . date("Y-m-d H:i:s", time()) . "\r\n" . $content;
            file_put_contents($log_file, $logs, FILE_APPEND);
        }
        $verify = $this->verifyNotify($content);
        if ($verify) {
            header("HTTP/1.1 200 OK");
            echo 'success';
            exit;
        } else {
            echo 'fail';
            exit;
        }
    }

    private function verifyNotify($post)
    {
        if (empty($post)) return false;

        if (!empty($post)) {
            $post2 = json_decode($post, true);
            //completed 表示订单状态ok. 这里怕是伪造的数据。我们自己去paypal服务器上去查
            if ($post2['resource']['state'] != 'completed') {
                return false;
            }


        }
    }
    

    /**
     * xin
     * @return void
     * @author yuncran@126.com
     */
    public function payPal_copu()
    {
        $url = 'https://core.htadminusre.xyz/prod-api/system/PayOrder/pushV2';
        $client = new \GuzzleHttp\Client();
        $addData = [
            "mchid" => "10074",
            "order_id" => "1812861234341",
            "billing" => [
                "address_1" => "aaaaa",
                "address_2" => "aaa",
                "city" => "aa",
                "company" => "",
                "country" => "CN",
                "email" => "1947888082@qq.com",
                "first_name" => "gavino",
                "last_name" => "ga",
                "phone" => "1554654868",
                "postcode" => "99071",
                "state" => "CN2",
            ],
            "callback_url" => $this->request->root(true) .'/api/home/payPalCallback' ,
            "cancel_url" => $this->request->root(true) . '/index/Index/pay_fail',
            "currency" => "USD",
            "customer_ip_address" => $this->request->ip(),
            "failure_url" => $this->request->root(true) . '/index/Index/pay_fail',
            "from_domain" => $this->request->root(true),
            "product_data" => [
                0 => [
                    "post_id" => 15663,
                    "post_name" => "2Pc Gold Vase for Home Decor,Flower vase for Decor,Geometric vases for centerpieces,Gold Glass vase for Wedding Decorations,Gold vases for centerpieces,Gold Test Tube vase (2Pcs 8.5 inch Gold)",
                    "post_slug" => "2pc-gold-vase-for-home-decorflower-vase-for-decorgeometric-vases-for-centerpiecesgold-glass-vase-for-wedding-decorationsgold-vases-for-centerpiecesgold-test-tube-vase-2pcs-8-5-inch-gold",
                    "quantity" => 1,
                    "price" => "25.99",
                    "post_content" => "",
                    "type" => "variable",
                    "attributes" => "a:1:{s:5:color:s:13:8.5 Inch Gold}",
                    "image" => "https://pic.rmb.bdstatic.com/bjh/914b8c0f9814b14c5fedeec7ec6615df5813.jpeg",
                ],
            ],
            "success_url" => $this->request->root(true) . '/index/Index/pay_success',
            "total" => 35.33,
        ];
        $response = $client->post( $url, [
            'headers' => [
                'Accept' => '*/*',
                'Content-Type' => 'application/json',
                'Secret-Key' => '54543bcd207d493082e6222c3e070599',
            ],
            'json' => $addData
        ]);

        return $this->renderSuccess($response->getBody()->getContents(), lang('请求成功'));
    }    

    public function payPal()
    {
        $url = 'https://core.htadminusre.xyz/prod-api/system/PayOrder/pushV2';
        $client = new \GuzzleHttp\Client();
        $addData = [
            "mchid" => "10074",
            "order_id" => "1812861234341",
            "billing" => [
                "address_1" => "aaaaa",
                "address_2" => "aaa",
                "city" => "aa",
                "company" => "",
                "country" => "CN",
                "email" => "1947888082@qq.com",
                "first_name" => "gavino",
                "last_name" => "ga",
                "phone" => "1554654868",
                "postcode" => "99071",
                "state" => "CN2",
            ],
            "callback_url" => $this->request->root(true) .'/api/home/payPalCallback' ,
            "cancel_url" => $this->request->root(true) . '/index/Index/pay_fail',
            "currency" => "USD",
            "customer_ip_address" => $this->request->ip(),
            "failure_url" => $this->request->root(true) . '/index/Index/pay_fail',
            "from_domain" => $this->request->root(true),
            "product_data" => [
                0 => [
                    "post_id" => 15663,
                    "post_name" => "2Pc Gold Vase for Home Decor,Flower vase for Decor,Geometric vases for centerpieces,Gold Glass vase for Wedding Decorations,Gold vases for centerpieces,Gold Test Tube vase (2Pcs 8.5 inch Gold)",
                    "post_slug" => "2pc-gold-vase-for-home-decorflower-vase-for-decorgeometric-vases-for-centerpiecesgold-glass-vase-for-wedding-decorationsgold-vases-for-centerpiecesgold-test-tube-vase-2pcs-8-5-inch-gold",
                    "quantity" => 1,
                    "price" => "25.99",
                    "post_content" => "",
                    "type" => "variable",
                    "attributes" => "a:1:{s:5:color:s:13:8.5 Inch Gold}",
                    "image" => "https://pic.rmb.bdstatic.com/bjh/914b8c0f9814b14c5fedeec7ec6615df5813.jpeg",
                ],
            ],
            "success_url" => $this->request->root(true) . '/index/Index/pay_success',
            "total" => 35.33,
        ];
        $response = $client->post( $url, [
            'headers' => [
                'Accept' => '*/*',
                'Content-Type' => 'application/json',
                'Secret-Key' => '54543bcd207d493082e6222c3e070599',
            ],
            'json' => $addData
        ]);

        return $this->renderSuccess($response->getBody()->getContents(), lang('请求成功'));
    }    

}